package com.cn.crypt;

import java.security.MessageDigest;

import org.apache.axiom.om.util.Base64;

import com.cn.xc.utils.CharacterUtil;
import com.cn.xc.utils.StringUtil;

/**
 * FUN: MD5
 * 
 * @author sushy
 * @date 2016-3-23
 */
public class Md5Cryption {

	/**
	 * @param data   源二进制数据
	 * @return MD5签名后的二进制数据
	 * @throws Exception
	 */
	public static byte[] byteArrayEncryptMD5(byte[] data) throws Exception {
		MessageDigest alga = MessageDigest.getInstance("MD5");
		alga.update(data);
		byte[] result = alga.digest();
		return result;
	}

	/**
	 * 
	 * @param data
	 *            明文
	 * @return MD5加密后使用BASE64编码的MD5签名
	 * @throws Exception
	 */
	public static String base64EncryptMD5(String data) throws Exception {
		byte[] bResult = byteArrayEncryptMD5(data.getBytes());
		String result = Base64.encode(bResult);
		return result;
	}

	/**
	 * @param strPwd
	 *            需要加密的字符串
	 * @return 加密后的字符串
	 * @throws Exception
	 */
	public String EncryptMD5(String strPwd) throws Exception {
		byte[] data = strPwd.getBytes();
		try {
			MessageDigest alga = MessageDigest.getInstance("MD5");
			alga.update(data);
			byte[] result = alga.digest();
			String strTeturn = StringUtil.byte2hex(result);
			return strTeturn;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
	}

	/**
	 * @param strPwd
	 *            需要加密的字符串
	 * @return 加密后的字符串
	 * @throws Exception
	 */
	public boolean IsEqualMD5(String strPwd, String mmPwd) throws Exception {
		boolean boolReturn = false;
		byte[] data = strPwd.getBytes();
		try {
			/**
			 * alga 密码加密后的
			 */
			MessageDigest alga = MessageDigest.getInstance("MD5");
			alga.update(data);
			byte[] result = alga.digest();
			byte byteMMPwd[] = new byte[mmPwd.length() / 2];
			for (int i = 0; i < mmPwd.length() / 2; i++) {
				byteMMPwd[i] = (byte) ((CharacterUtil.Char2Byte(mmPwd.charAt(2 * i)) * 0x10 + CharacterUtil
						.Char2Byte(mmPwd.charAt(2 * i + 1))) & 0XFF);
			}
			if (MessageDigest.isEqual(byteMMPwd, result)) {
				boolReturn = true;
			}
			return boolReturn;
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
	}

	public static void main(String[] args) throws Exception {
		String ming = "1234567你好吗";
		String mi = Md5Cryption.base64EncryptMD5(ming);
		System.out.println(mi);
	}

}
